// eyeHealth.js
// 导入API工具函数
const apiUtils = require('../../utils/apiUtils.js');

Page({
  data: {
    // 文章详情数据
    article: {
      id: '',
      title: '加载中...',
      author: '',
      publishDate: '',
      readCount: 0,
      coverImage: '',
      content: '<div class="rich-text-content"><p>文章加载中...</p></div>'
    },
    
    // 文章列表数据（用于分页显示）
    articleList: [],
    
    // 分页数据
    currentPage: 1,    // 当前页码，默认为1（最新文章）
    pageSize: 5,       // 每页显示的文章数量
    totalCount: 0,     // 文章总数量
    hasMore: true,     // 是否有更多数据
    loading: false,    // 是否正在加载中
    
    // 相关推荐文章
    relatedArticles: [],
    
    // 用户交互状态
    isLiked: false,
    isFavorited: false,
    likeCount: 0
  },

  onLoad: function(options) {
    // 如果有文章ID参数，则根据ID获取文章详情
    if (options.id) {
      this.getArticleDetail(options.id);
    } else {
      // 初始化分页数据，默认加载最新文章（第一页）
      this.loadArticles(1);
    }
    // 初始化页面数据
    this.initPageData();
  },
  
  // 页面上拉触底事件处理函数（用于分页加载）
  onReachBottom: function() {
    // 如果有更多数据且当前不在加载中，则加载下一页
    if (this.data.hasMore && !this.data.loading) {
      const nextPage = this.data.currentPage + 1;
      this.loadArticles(nextPage);
    }
  },
  
  // 初始化页面数据
  initPageData: function() {
    // 这里可以从本地存储中获取用户对当前文章的点赞和收藏状态
    const articleId = this.data.article.id || 'current';
    const likedArticles = wx.getStorageSync('likedArticles') || [];
    const favoritedArticles = wx.getStorageSync('favoritedArticles') || [];
    
    this.setData({
      isLiked: likedArticles.includes(articleId),
      isFavorited: favoritedArticles.includes(articleId)
    });
  },
  
  // 获取文章详情
  getArticleDetail: async function(articleId) {
    // 显示加载提示
    wx.showLoading({
      title: '加载中...',
    });
    
    try {
      // 调用API获取文章详情
      const articleData = await apiUtils.getArticleDetail(articleId);
      
      // 转换数据格式以匹配页面需求
      const formattedArticle = {
        id: articleData.id,
        title: articleData.title,
        author: '艾极光健康专家',
        publishDate: articleData.publish_date,
        readCount: Math.floor(Math.random() * 2000) + 1000, // 随机生成阅读量
        coverImage: articleData.cover_image || '/images/article1.png',
        content: articleData.content || '<div class="rich-text-content"><p>暂无内容</p></div>'
      };
      
      // 更新文章数据
      this.setData({
        article: formattedArticle
      });
      
      // 重新初始化页面状态（点赞、收藏等）
      this.initPageData();
      
    } catch (error) {
      console.error('获取文章详情失败:', error);
      wx.showToast({
        title: '获取文章详情失败',
        icon: 'none',
        duration: 2000
      });
    } finally {
      // 隐藏加载提示
      wx.hideLoading();
    }
  },
  
  // 加载文章列表（支持分页）
  loadArticles: async function(page) {
    // 如果已经没有更多数据或者正在加载中，则不重复加载
    if (!this.data.hasMore || this.data.loading) {
      return;
    }
    
    // 设置加载状态为true
    this.setData({
      loading: true
    });
    
    // 显示加载提示
    wx.showLoading({
      title: '加载中...',
    });
    
    try {
      // 调用API获取文章列表
      const articlesData = await apiUtils.getArticles(page, this.data.pageSize);
      
      // 转换数据格式以匹配页面需求
      const formattedArticles = articlesData.articles.map(article => ({
        id: article.id,
        title: article.title,
        author: '艾极光健康专家',
        publishDate: article.publish_date,
        readCount: Math.floor(Math.random() * 2000) + 1000, // 随机生成阅读量
        coverImage: article.cover_image || '/images/article1.png',
        content: article.summary ? `<div class="rich-text-content"><p>${article.summary}</p></div>` : '<div class="rich-text-content"><p>暂无内容</p></div>'
      }));
      
      // 如果是首次加载
      if (page === 1) {
        // 如果有文章，则显示第一篇文章
        if (formattedArticles.length > 0) {
          this.setData({
            article: formattedArticles[0]
          });
          
          // 初始化相关推荐文章（取接下来的3篇作为最新的三篇相关推荐）
          const relatedArticles = formattedArticles.slice(1, 4).map(article => ({
            id: article.id,
            title: article.title,
            image: article.coverImage,
            date: article.publishDate
          }));
          
          this.setData({
            relatedArticles: relatedArticles,
            // 从文章列表中移除相关推荐的文章，确保它们不显示在"更多文章"中
            articleList: formattedArticles.slice(4) // 从第5篇文章开始作为更多文章的内容
          });
        }
      } else {
        // 非首次加载时，追加文章到列表
        // 确保也只添加除前四篇外的文章，保持与首次加载逻辑一致
        this.setData({
          articleList: [...this.data.articleList, ...formattedArticles]
        });
      }
      
      // 更新分页数据
      this.setData({
        currentPage: page,
        totalCount: articlesData.total,
        hasMore: articlesData.has_next,
        loading: false
      });
      
    } catch (error) {
      console.error('获取文章列表失败:', error);
      wx.showToast({
        title: '获取文章列表失败',
        icon: 'none',
        duration: 2000
      });
      
      this.setData({
        loading: false
      });
    } finally {
      // 隐藏加载提示
      wx.hideLoading();
    }
  },
  
  // 切换到指定文章
  switchToArticle: function(e) {
    const articleId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/eyeHealth/eyeHealth?id=${articleId}`
    });
  },
  
  // 点赞功能
  onLike: function() {
    const isLiked = !this.data.isLiked;
    const likeCount = isLiked ? this.data.likeCount + 1 : this.data.likeCount - 1;
    
    this.setData({
      isLiked: isLiked,
      likeCount: likeCount
    });
    
    // 保存点赞状态到本地存储
    const articleId = this.data.article.id || 'current';
    let likedArticles = wx.getStorageSync('likedArticles') || [];
    
    if (isLiked) {
      if (!likedArticles.includes(articleId)) {
        likedArticles.push(articleId);
      }
    } else {
      likedArticles = likedArticles.filter(id => id !== articleId);
    }
    
    wx.setStorageSync('likedArticles', likedArticles);
    
    // 模拟点赞成功提示
    wx.showToast({
      title: isLiked ? '点赞成功' : '取消点赞',
      icon: 'success',
      duration: 1500
    });
  },
  
  // 收藏功能
  onFavorite: function() {
    const isFavorited = !this.data.isFavorited;
    
    this.setData({
      isFavorited: isFavorited
    });
    
    // 保存收藏状态到本地存储
    const articleId = this.data.article.id || 'current';
    let favoritedArticles = wx.getStorageSync('favoritedArticles') || [];
    
    if (isFavorited) {
      if (!favoritedArticles.includes(articleId)) {
        favoritedArticles.push(articleId);
      }
    } else {
      favoritedArticles = favoritedArticles.filter(id => id !== articleId);
    }
    
    wx.setStorageSync('favoritedArticles', favoritedArticles);
    
    // 模拟收藏成功提示
    wx.showToast({
      title: isFavorited ? '收藏成功' : '取消收藏',
      icon: 'success',
      duration: 1500
    });
  },
  
  // 分享功能
  onShare: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  
  // 跳转到相关文章
  navigateToArticle: function(e) {
    const articleId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/eyeHealth/eyeHealth?id=${articleId}`
    });
  },
  
  // 返回上一页
  navigateBackHome: function() {
    wx.navigateBack();
  },
  
  // 分享给朋友
  onShareAppMessage: function() {
    return {
      title: this.data.article.title,
      path: `/pages/eyeHealth/eyeHealth?id=${this.data.article.id}`,
      imageUrl: this.data.article.coverImage
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: this.data.article.title,
      query: `id=${this.data.article.id}`,
      imageUrl: this.data.article.coverImage
    };
  }
})